package es.andresimon.portfolio.security;

import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;
import es.andresimon.portfolio.security.PortfolioUser;

@Configurable
@Component
public class PortfolioUserDataOnDemand {

	private Random rnd = new java.security.SecureRandom();

	private List<PortfolioUser> data;

	public PortfolioUser getNewTransientPortfolioUser(int index) {
        es.andresimon.portfolio.security.PortfolioUser obj = new es.andresimon.portfolio.security.PortfolioUser();
        java.lang.String email = "email_" + index;
        if (email.length() > 100) {
            email  = email.substring(0, 100);
        }
        obj.setEmail(email);
        java.lang.String login = "login_" + index;
        if (login.length() > 10) {
            login  = login.substring(0, 10);
        }
        obj.setLogin(login);
        java.lang.String name = "name_" + index;
        if (name.length() > 100) {
            name  = name.substring(0, 100);
        }
        obj.setName(name);
        java.lang.String password = "password_" + index;
        if (password.length() > 10) {
            password  = password.substring(0, 10);
        }
        obj.setPassword(password);
        obj.setUserRole(null);
        return obj;
    }

	public PortfolioUser getSpecificPortfolioUser(int index) {
        init();
        if (index < 0) index = 0;
        if (index > (data.size() - 1)) index = data.size() - 1;
        PortfolioUser obj = data.get(index);
        return PortfolioUser.findPortfolioUser(obj.getId());
    }

	public PortfolioUser getRandomPortfolioUser() {
        init();
        PortfolioUser obj = data.get(rnd.nextInt(data.size()));
        return PortfolioUser.findPortfolioUser(obj.getId());
    }

	public boolean modifyPortfolioUser(PortfolioUser obj) {
        return false;
    }

	public void init() {
        data = es.andresimon.portfolio.security.PortfolioUser.findPortfolioUserEntries(0, 10);
        if (data == null) throw new IllegalStateException("Find entries implementation for 'PortfolioUser' illegally returned null");
        if (!data.isEmpty()) {
            return;
        }
        
        data = new java.util.ArrayList<es.andresimon.portfolio.security.PortfolioUser>();
        for (int i = 0; i < 10; i++) {
            es.andresimon.portfolio.security.PortfolioUser obj = getNewTransientPortfolioUser(i);
            obj.persist();
            obj.flush();
            data.add(obj);
        }
    }
}
